﻿using System.Threading.Tasks;
using System.Windows.Forms;
using Ast.Core.WinApi;
using Ast.Framework;

namespace Ast.Core.Services
{
    public interface IKeyboardService : IDependency
    {
        Task PressKey(Keys key, int delay);
    }

    public class KeyboardService : IKeyboardService
    {
        private readonly IDeviceController _deviceController;

        public KeyboardService(IDeviceController deviceController)
        {
            _deviceController = deviceController;
        }

        public async Task PressKey(Keys key, int delay)
        {
            // down
            var makeCode = (ushort) Native.MapVirtualKey((uint) key, Constant.MAPVK_VK_TO_VSC);
            var input = new Structure.KeyboardInputData {Flags = Constant.KeyMake, MakeCode = makeCode};
            _deviceController.Send(IoCtl.IoCtlKeyboard, input);

            await Task.Delay(delay);

            // up
            input.Flags = Constant.KeyBreak;
            _deviceController.Send(IoCtl.IoCtlKeyboard, input);
        }
    }

    public static class KeyboardServiceExtension
    {
        public static async Task PressKey(this IKeyboardService keyboardService, Keys key)
        {
            await keyboardService.PressKey(key, 50);
        }
    }
}